<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`${currentRole?.name || ''} - ${$t('page.system.userRole.userList')}`"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="role-users">
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAssignUser">
          + {{ $t('page.system.userRole.assignUser') }}
        </el-button>
        <el-button 
          type="danger" 
          :disabled="selectedUsers.length === 0"
          @click="handleBatchRemove"
        >
          {{ $t('page.system.userRole.removeUser') }}
        </el-button>
      </div>

      <!-- 用户列表 -->
      <el-table
        v-loading="loading"
        :data="userList"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="username"
          :label="$t('page.system.userRole.username')"
          min-width="120"
        />
        <el-table-column
          prop="realName"
          :label="$t('page.system.userRole.realName')"
          min-width="120"
        />
        <el-table-column
          prop="email"
          :label="$t('page.system.userRole.email')"
          min-width="180"
          show-overflow-tooltip
        />
        <el-table-column
          prop="phone"
          :label="$t('page.system.userRole.phone')"
          min-width="120"
        />
        <el-table-column
          prop="status"
          :label="$t('page.system.userRole.status')"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'danger'">
              {{ row.status === 0 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('page.system.userRole.operation')"
          width="120"
          align="center"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              size="small"
              type="danger"
              text
              @click="handleRemoveUser(row)"
            >
              {{ $t('page.system.userRole.removeUser') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t('page.system.userRole.cancel') }}
        </el-button>
      </div>
    </template>

    <!-- 用户分配弹窗 -->
    <UserRoleAssignModal
      v-model:visible="assignModalVisible"
      :users="availableUsers"
      @success="handleAssignSuccess"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import {
  ElButton,
  ElDialog,
  ElMessage,
  ElMessageBox,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';

import type { Role } from '#/api/system/role';
import type { UserInfo } from '#/api/system/userRole';
import { getRoleUsersApi, removeUserRoleApi } from '#/api/system/userRole';
import { getUserInfoApi } from '#/api/core/auth';
import { $t } from '#/locales';

import UserRoleAssignModal from './UserRoleAssignModal.vue';

interface Props {
  visible: boolean;
  role: Role | null;
  allUsers: UserInfo[]; // 所有可用用户列表
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'refresh'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const loading = ref(false);
const userList = ref<UserInfo[]>([]);
const selectedUsers = ref<UserInfo[]>([]);
const assignModalVisible = ref(false);
const currentRole = ref<Role | null>(null);

// 可分配的用户列表（排除已分配的用户）
const availableUsers = computed(() => {
  const assignedUserIds = userList.value.map(user => user.id);
  const available = props.allUsers.filter(user => !assignedUserIds.includes(user.id));
  console.log('RoleUsersModal - 所有用户数量:', props.allUsers.length);
  console.log('RoleUsersModal - 已分配用户数量:', assignedUserIds.length);
  console.log('RoleUsersModal - 可分配用户数量:', available.length);
  return available;
});

// 获取角色用户列表
const getRoleUsers = async () => {
  if (!currentRole.value) return;
  
  loading.value = true;
  try {
    // 1. 获取用户ID数组
    const userIds = await getRoleUsersApi(currentRole.value.id);
    
    // 2. 批量获取用户详细信息
    const userPromises = userIds.map(userId => getUserInfoApi(userId));
    const userResponses = await Promise.all(userPromises);
    
    // 3. 转换用户数据格式
    userList.value = userResponses.map(userData => ({
      id: userData.id,
      username: userData.username,
      realName: userData.realName || '',
      email: '', // 当前API响应中没有email字段
      phone: userData.phone,
      status: userData.status || 0,
      roles: userData.role ? [userData.role] : []
    }));
  } catch (error) {
    console.error('获取角色用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 监听角色变化
watch(
  () => props.role,
  (role) => {
    currentRole.value = role;
    if (role && props.visible) {
      getRoleUsers();
    }
  },
  { immediate: true }
);

// 监听弹窗显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible && currentRole.value) {
      getRoleUsers();
      selectedUsers.value = [];
    }
  }
);

// 处理选择变更
const handleSelectionChange = (selection: UserInfo[]) => {
  selectedUsers.value = selection;
};

// 分配用户
const handleAssignUser = () => {
  assignModalVisible.value = true;
};

// 移除单个用户
const handleRemoveUser = async (user: UserInfo) => {
  if (!currentRole.value) return;
  
  try {
    await ElMessageBox.confirm(
      $t('page.system.userRole.message.removeConfirm'),
      $t('page.system.userRole.removeUser'),
      {
        type: 'warning',
      }
    );

    await removeUserRoleApi(user.id, currentRole.value.id);
    ElMessage.success($t('page.system.userRole.message.removeSuccess'));
    getRoleUsers();
    emit('refresh');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除用户失败:', error);
    }
  }
};

// 批量移除用户
const handleBatchRemove = async () => {
  if (!currentRole.value || selectedUsers.value.length === 0) return;
  
  try {
    await ElMessageBox.confirm(
      $t('page.system.userRole.message.removeUserConfirm'),
      $t('page.system.userRole.removeUser'),
      {
        type: 'warning',
      }
    );

    const promises = selectedUsers.value.map(user => 
      removeUserRoleApi(user.id, currentRole.value!.id)
    );
    
    await Promise.all(promises);
    ElMessage.success($t('page.system.userRole.message.removeSuccess'));
    getRoleUsers();
    emit('refresh');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量移除用户失败:', error);
    }
  }
};

// 分配成功回调
const handleAssignSuccess = () => {
  getRoleUsers();
  emit('refresh');
};

// 关闭弹窗
const handleClose = () => {
  selectedUsers.value = [];
  dialogVisible.value = false;
};
</script>

<style scoped>
.role-users {
  max-height: 600px;
  overflow-y: auto;
}

.toolbar {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style> 
